package com.g3net.templeteEngine;

import java.io.StringWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import com.g3net.tool.StringUtils;

/**
 * 模版处理器，用于拼装页面以及数据
 * @author yuxiaowei
 *
 */
public class TempleteProcesser {
	private static Logger log = Logger.getLogger(TempleteProcesser.class);
	/**
	 * 
	 * @param tname	当这个参数没有的时候，采用动态模板进行操作
	 * @param tcontent
	 * @param vars
	 * @return
	 */
	public static String process(String tname,String tcontent,Map<String,Object> vars){
		/**
		 * 初始化上下文环境
		 */
		VelocityContext context = new VelocityContext();
		if(vars!=null)
		{
			Iterator<String> keys=vars.keySet().iterator();
			while (keys.hasNext()) {
				String key = (String) keys.next();
				context.put(key, vars.get(key));
			}
		}
		StringWriter w = new StringWriter();
		if(StringUtils.hasText(tname))
		{
			Velocity.mergeTemplate(tname, "utf-8", context, w );
		}else{//调用动态模板
			try
	        {
	            Velocity.evaluate( context, w, "dynamic", tcontent );
	        }
	        catch( Exception pee )
	        {
	        	log.error("", pee);
	        }
		}
		return w.toString();
	}
	
	public static void main(String[] args) {
		TempleteManager.addTemplete("test", "We are using $project:$name #set ($i = 14+1) $i to render this.");
		Map<String,Object> vars=new HashMap<String,Object>();
		vars.put("project", "ggbook");
		vars.put("name", "test");
//		vars.put("i", "1");
		for (int i = 0; i < 1; i++) {
			long start=System.currentTimeMillis();
			String r=process("test", "", vars);
			long end=System.currentTimeMillis();
			System.out.println(r+" times="+(end-start));
			
			r=process("", "We are using dynamic  $project:$name to render this.", vars);
			System.out.println(r);
		}
		
	}
	
}
